package com.foldingleaf.web.controller.order;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * TODO 微信验证方法
 *
 * @author xiaoshuaishuai
 * @date 2019-08-29 15:08
 */
@RestController
public class WeChatVerify {

    /**
     * 微信服务器地址验证
     *
     * @param signature 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @param echostr   随机字符串
     * @return 返回echostr字符串
     */
    @GetMapping(value = "/verifyDeveloper")
    public String verifyDeveloper(String signature, String timestamp, String nonce, String echostr, HttpServletResponse response) {
        StringBuilder stringBuilder = new StringBuilder();
        List<String> list = new ArrayList<>(4);
        String token = "Jiangyijian0323Wechat20220625";
        list.add(token);
        list.add(timestamp);
        list.add(nonce);
        Collections.sort(list);
        for (String item : list) {
            stringBuilder.append(item);
        }
        String result = DigestUtils.sha1Hex(stringBuilder.toString());
        if (signature.equals(result)) {
            return echostr;
        } else {
            return null;
        }
    }
    /**
     * 获取openid
     * @param
     * @param
     * @return
     */
    @CrossOrigin
    @GetMapping("/getopenid")
    @ResponseBody
    public String getopenid(String code, HttpServletRequest request, HttpServletResponse response){
        String appid= "wx61f4fbd46508977d";
        String secret = "728011842295378d2e7de47167f2c7e7";
        response.setHeader("Access-Control-Allow-Origin", "*");
        /*星号表示所有的域都可以接受，*/
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");
        String wxLoginUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";
        String param = "appid="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
        String jsonString = GetPostUntil.sendGet(wxLoginUrl, param);
        JSONObject json = JSONObject.parseObject(jsonString);
        String openid = json.getString("openid");
        System.out.println("###############"+openid);
        return openid;
    }



}



